import React, { Component } from 'react'
import {
  StyleSheet,
  Text,
  View,
  Image,
  TextInput,
  Modal,
  TouchableOpacity,
  Dimensions,
  AlertIOS,
  AsyncStorage
} from 'react-native'
import Icon from 'react-native-vector-icons/Ionicons'
import Button from 'react-native-button'
import ImagePicker from 'react-native-image-picker'
import * as Progress from 'react-native-progress'
import request from '../common/request'
import { api, cloudinary, qiniu } from '../common/config'

const width = Dimensions.get('window').width

// Cloudinary 上传
function getAvatarUrl(avatar, type) {
  // 直接存url
  if (typeof avatar === 'string') {
    if (avatar.indexOf('http') > -1 || avatar.indexOf('data:image') > -1) return avatar
  }

  // 存Cloudinary 返回的public_id
  if (avatar.indexOf('avatar/') > -1) {
    return cloudinary.base + '/' + type + '/upload/v' + avatar.version + '/' + avatar.public_id + '.' + avatar.format
  }

  // 存七牛返回的key
  return qiniu.base + avatar

}


class Account extends Component {
  constructor(props) {
    super(props)

    this.state = {
      user: this.props.user || {},
      avatarProgress: 0.01,
      avatarUploading: false,
      modalVisible: false,
    }
  }

  componentDidMount() {
    AsyncStorage.getItem('user')
      .then(data => {
        let user
        if (data) {
          user = JSON.parse(data)
        }

        if (user && user.accessToken) {
          this.setState({
            user: user
          })
        }
      })
  }

  _edit() {
    this.setState({
      modalVisible: true
    })
  }

  _closeModal() {
    this.setState({
      modalVisible: false
    })
  }

  _changeUserState(key, value) {
    let user = this.state.user

    user[key] = value

    this.setState({
      user: user
    })
  }

  _submit() {
    this._asyncUser()
  }

  _logout() {
    this.props.logout()
  }

  _getQiniuToken() {
    const accessToken = this.state.user.accessToken
    const signatureUrl = api.base + api.signature

    return request.post(signatureUrl, {
      accessToken: accessToken,
      type: 'avatar',
      cloud: 'qiniu',
    }).catch(error => {
      console.warn(error)
    })
  }

  _pickPhoto() {
    const photoOptions = {
      title: '选择头像',
      cancelButtonTitle: '取消',
      takePhotoButtonTitle: '拍照',
      chooseFromLibraryButtonTitle: '从相册选择',
      quality: 0.75,
      allowsEditing: true,
      noData: false,
      storageOptions: {
        skipBackup: true,
        path: 'images'
      },
    }

    ImagePicker.showImagePicker(photoOptions, res => {
      if (res.didCancel) return
      // Cloudinary 参数
      // const avatarData = 'data:image/jpeg;base64,' + res.data
      // const timestamp = Date.now()
      // const tags = 'app,avatar'
      // const folder = 'avatar'
      // const signatureUrl = api.base + api.signature
      const uri = res.uri

      // 七牛上传
      this._getQiniuToken()
        .then(data => {
          if (data && data.success) {
            const token = data.data.token
            const key = data.data.key

            let body = new FormData()
            body.append('token', token)
            body.append('key', key)
            body.append('file', {
              type: 'image/jpeg',
              uri: uri,
              name: key
            })

            this._upload(body)
          }
        })

      // Cloudinary 上传
      // request.post(signatureUrl, {
      //   accessToken: accessToken,
      //   timestamp: timestamp,
      //   type: 'avatar',
      //   key: key
      // }).then(data => {
      //   if (data && data.success) {
      //     const signature = data.data

      //     let body = new FormData()
      //     body.append('folder', folder)
      //     body.append('signature', signature)
      //     body.append('tags', tags)
      //     body.append('timestamp', timestamp)
      //     body.append('api_key', cloudinary.api_key)
      //     body.append('resource_type', 'image')
      //     body.append('file', avatarData)

      //     this._upload(body)
      //   }
      // }).catch(error => {
      //   console.warn(error)
      // })
    })
  }

  _upload(body) {
    let xhr = new XMLHttpRequest()
    // const url = cloudinary.image // Cloudinary 上传url
    const url = qiniu.uploadUrl

    this.setState({
      avatarUploading: true,
      avatarProgress: 0.01
    })

    xhr.open('POST', url)
    xhr.onload = () => {
      if (xhr.status !== 200) {
        AlertIOS.alert('请求失败')
        console.log(xhr.responseText)

        return
      }

      if (!xhr.responseText) {
        AlertIOS.alert('请求失败')

        return
      }

      let response

      try {
        response = JSON.parse(xhr.response)
      }
      catch (e) {
        console.log(e)
        console.log('parse fails')
      }

      if (response) {
        let user = this.state.user

        // Cloudinary 上传
        if (response.public_id) {
          user.avatar = response.public_id
        }

        if (response.key) {
          user.avatar = response.key
        }

        this.setState({
          avatarUploading: false,
          avatarProgress: 0.01,
          user: user
        })

        this._asyncUser(true)
      }
    }

    // 上传进度
    if (xhr.upload) {
      xhr.upload.onprogress = event => {
        if (event.lengthComputable) {
          let percent = Number((event.loaded / event.total).toFixed(2))

          this.setState({
            avatarProgress: percent
          })
        }
      }
    }

    xhr.send(body)
  }

  _asyncUser(isAvatar) {
    let user = this.state.user

    if (user && user.accessToken) {
      let url = api.base + api.updateAccount

      request.post(url, user)
        .then(data => {
          if (data && data.success) {
            user.avatar = data.data

            if (isAvatar) AlertIOS.alert('头像更新成功！')

            this.setState({
              user: user
            }, () => {
              this._closeModal()
              AsyncStorage.setItem('user', JSON.stringify(user))
            })
          }
        })
        .catch(error => {
          console.warn(error)
        })

    }

  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.toolbar}>
          <Text style={styles.toolbarTitle}>我的账户</Text>
          <Text style={styles.toolbarExtra} onPress={() => { this._edit() }}>编辑</Text>
        </View>

        {
          this.state.user.avatar
            ? <TouchableOpacity style={styles.avatarContainer} onPress={this._pickPhoto.bind(this)}>
              <Image
                source={{ uri: getAvatarUrl(this.state.user.avatar, 'image') }}
                style={styles.avatarContainer}>
                <View style={styles.avatarBox}>
                  {
                    this.state.avatarUploading
                      ? <Progress.Pie
                        size={60}
                        showsText={true}
                        color={'rgba(255,255,255,.5)'}
                        progress={this.state.avatarProgress} />
                      : <Image
                        source={{ uri: getAvatarUrl(this.state.user.avatar, 'image') }}
                        style={styles.avatar} />
                  }

                </View>
                <Text style={styles.avatarTip}>修改头像</Text>
              </Image>
            </TouchableOpacity >
            : <TouchableOpacity style={styles.avatarContainer} onPress={this._pickPhoto.bind(this)}>
              <View>
                <Text style={styles.avatarTip}>添加头像</Text>
                <View style={styles.avatarBox}>
                  {
                    this.state.avatarUploading
                      ? <Progress.Pie
                        size={60}
                        showsText={true}
                        color={'rgba(255,255,255,.5)'}
                        progress={this.state.avatarProgress}
                      />
                      : <Icon
                        name='ios-add'
                        style={styles.plusIcon}
                      />
                  }
                </View>
              </View>
            </TouchableOpacity>
        }

        <Modal
          visible={this.state.modalVisible}>
          <View style={styles.modalContainer}>
            <Icon
              onPress={this._closeModal.bind(this)}
              name='ios-close'
              style={styles.closeIcon} />
            <View style={styles.fieldItem}>
              <Text style={styles.label}>昵称</Text>
              <TextInput
                placeholder='输入你的昵称'
                style={styles.inputField}
                autoCapitalize={'none'}
                autoCorrect={false}
                defaultValue={this.state.user.nickname}
                onChangeText={text => {
                  this._changeUserState('nickname', text)
                }}
              />
            </View>

            <View style={styles.fieldItem}>
              <Text style={styles.label}>年龄</Text>
              <TextInput
                placeholder='输入你的年龄'
                style={styles.inputField}
                autoCapitalize={'none'}
                autoCorrect={false}
                defaultValue={this.state.user.age}
                onChangeText={text => {
                  this._changeUserState('age', text)
                }}
              />
            </View>

            <View style={styles.fieldItem}>
              <Text style={styles.label}>年龄</Text>
              <Icon.Button
                onPress={() => {
                  this._changeUserState('gender', 'male')
                }}
                style={[
                  styles.gender,
                  this.state.user.gender === 'male' && styles.genderSelected
                ]}
                name='ios-male'
              >男</Icon.Button>
              <Icon.Button
                onPress={() => {
                  this._changeUserState('gender', 'female')
                }}
                style={[
                  styles.gender,
                  this.state.user.gender === 'female' && styles.genderSelected
                ]}
                name='ios-female'
              >女</Icon.Button>
            </View>

            <View style={styles.fieldItem}>
              <Text style={styles.label}>真名</Text>
              <TextInput
                placeholder='输入你的真名'
                style={styles.inputField}
                autoCapitalize={'none'}
                autoCorrect={false}
                defaultValue={this.state.user.realname}
                onChangeText={text => {
                  this._changeUserState('realname', text)
                }}
              />
            </View>

            <View style={styles.fieldItem}>
              <Text style={styles.label}>身高</Text>
              <TextInput
                placeholder='输入你的身高'
                style={styles.inputField}
                autoCapitalize={'none'}
                autoCorrect={false}
                defaultValue={this.state.user.height}
                onChangeText={text => {
                  this._changeUserState('height', text)
                }}
              />
            </View>

            <Button style={styles.submitBtn} onPress={() => { this._submit() }}>保存</Button>
          </View>
        </Modal>

        <Button style={styles.submitBtn} onPress={() => { this._logout() }}>退出</Button>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1
  },

  toolbar: {
    flexDirection: 'row',
    paddingTop: 25,
    paddingBottom: 12,
    backgroundColor: '#ee753c'
  },

  toolbarTitle: {
    flex: 1,
    fontSize: 16,
    color: '#fff',
    textAlign: 'center',
    fontWeight: '600'
  },

  toolbarExtra: {
    position: 'absolute',
    right: 10,
    top: 26,
    color: '#fff',
    textAlign: 'right',
    fontWeight: '600',
    fontSize: 14
  },

  avatarContainer: {
    width: width,
    height: 140,
    alignItems: 'center',
    justifyContent: 'center',
    backgroundColor: '#666'
  },

  avatarBox: {
    marginTop: 15,
    alignItems: 'center',
    justifyContent: 'center'
  },


  avatarTip: {
    color: '#fff',
    backgroundColor: 'transparent',
    fontSize: 14
  },

  avatar: {
    marginBottom: 15,
    width: width * 0.2,
    height: width * 0.2,
    resizeMode: 'cover',
    borderWidth: 1,
    borderColor: '#ccc',
    borderRadius: width * 0.1
  },

  plusIcon: {
    padding: 10,
    paddingLeft: 20,
    paddingRight: 20,
    color: '#999',
    fontSize: 40,
    backgroundColor: '#fff'
  },

  modalContainer: {
    flex: 1,
    paddingTop: 50,
    backgroundColor: '#fff'
  },

  fieldItem: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    height: 50,
    paddingLeft: 15,
    paddingRight: 15,
    borderColor: '#eee',
    borderBottomWidth: 1
  },

  label: {
    color: '#ccc',
    marginRight: 10
  },

  closeIcon: {
    position: 'absolute',
    width: 40,
    height: 40,
    fontSize: 32,
    right: 10,
    top: 30,
    color: '#ee753c'
  },

  gender: {
    backgroundColor: '#ccc'
  },

  genderSelected: {
    backgroundColor: '#ee753c'
  },

  inputField: {
    flex: 1,
    height: 50,
    color: '#666',
    fontSize: 14
  },

  submitBtn: {
    width: width - 20,
    padding: 16,
    marginLeft: 10,
    marginRight: 10,
    marginTop: 40,
    marginBottom: 20,
    borderWidth: 1,
    borderColor: '#ee753c',
    backgroundColor: '#ee753c',
    borderRadius: 4,
    color: '#fff',
    fontSize: 18
  }

})

module.exports = Account